const jwt = require("jsonwebtoken");
const {
    createUser,
    getUserInfo,
    updateById,
} = require("../service/user.service");
const { userRegisterError } = require("../constant/err.type");
const { JWT_SECRET } = require("../config/config.default");

class UserController {
    //因为数据库操作都是异步，所以用async
    async register(ctx, next) {
        //获取数据
        const { user_name, password } = ctx.request.body;

        try {
            //操作数据库
            const result = await createUser(user_name, password);
            ctx.body = {
                code: 0,
                message: "注册成功",
                result: {
                    id: result.id,
                    user_name: result.user_name,
                },
            };
        } catch (error) {
            // console.log(error);
            ctx.app.emit("error", userRegisterError, ctx);
            return;
        }
    }

    async login(ctx, next) {
        const { user_name } = ctx.request.body;

        //在token的playload中，记录id，user_name，is_admin
        try {
            //剔除password  这里重复查询，可以优化，提前挂载到ctx上
            const { password, ...res } = await getUserInfo({ user_name });

            ctx.body = {
                code: 0,
                message: "用户登录成功",
                result: {
                    //设置token过期时间一天
                    token: jwt.sign(res, JWT_SECRET, { expiresIn: "1d" }),
                },
            };
        } catch (error) {
            return console.error("用户登录失败", error);
        }
    }

    async changePassword(ctx, next) {
        //获取数据
        const id = ctx.state.user.id;
        const password = ctx.request.body.password;
        //操作数据库
        if(await updateById({id, password})){
            ctx.body = {
                code: 0,
                message: "修改密码成功",
                result: '',
            }
        }else{
            ctx.body = {
                code: '10007',
                message: "修改密码失败",
                result: '',
            }
        }
    }
}

module.exports = new UserController();
